<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Agency;
use App\Models\Device;
use Illuminate\Http\Request;


class DeviceController extends BaseController
{
    /**
     *
     * @Date 2020/9/10 下午5:40
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function verify(Request $request)
    {
        $this->validate($request, [
            'code' => 'required|string',
        ], [], []);

        $device = Device::where("code", $request->input("code"))->first();
        if(empty($device)){
            $agencies = Agency::all(['id', 'name']);
            return $this->json(['is_register'=>0, 'agnecies'=>$agencies]);
        }

        return $this->json(['is_register'=>1]);
    }

    /**
     *
     * @Date 2020/9/10 下午5:41
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request){
        $this->validate($request, [
            'code' => 'required|string',
            'agency_id' => 'required|integer|exists:agencies,id',
        ], [], []);

        $data = $request->only(['code', 'agency_id']);
        $has = Device::where("code", $data['code'])->exists();

        if ($has){
            return $this->json([], config('apicode.isExist.code'), config('apicode.isExist.msg'));
        }
        $data = array_merge($data, ['kind_id'=>2, 'get_time'=>date("Y-m-d H:i:s")]);

        if (Device::create($data)){
            return $this->json();
        }

        return $this->json([], config('apicode.serverError.code'), config('apicode.serverError.msg'));
    }
}
